const http = require("http");
const fs = require("fs");
const url = require("url");
const etag = require("etag");

http
  .createServer((req, res) => {
    console.log(req.method, req.url);
    const { pathname } = url.parse(req.url);

    if (pathname === "/") {
      const data = fs.readFileSync("./index.html");
      res.end(data);
    } else if (pathname === "/defaultUser.png") {
      const data = fs.readFileSync("./defaultUser.png");
      res.writeHead(200, {
        Expires: new Date("2022-4-30 1:4:40").toUTCString(),
      });
      res.end(data);
    } else if (pathname === "/img-share-bg.png") {
      const data = fs.readFileSync("./img-share-bg.png");
      res.writeHead(200, {
        "Cache-Control": "max-age=5",
      });
      res.end(data);
    } else if (pathname === "/b_header.jpg") {
      const { mtime } = fs.statSync("./b_header.jpg");
      const ifModifiedSince = req.headers["if-modified-since"];

      if (ifModifiedSince === mtime.toUTCString()) {
        // 缓存生效
        res.statusCode = 304;
        res.end();
        return;
      }

      const data = fs.readFileSync("./b_header.jpg");
      res.setHeader("last-modified", mtime.toUTCString());
      res.setHeader("Cache-Control", "no-cache");
      res.end(data);
    } else if (pathname === "/img4.png") {
      const data = fs.readFileSync("./img4.png");
      const etagContent = etag(data);

      const ifNoneMatch = req.headers["if-none-match"];

      if (ifNoneMatch === etagContent) {
        // 缓存生效
        res.statusCode = 304;
        res.end();
        return;
      }

      res.setHeader("etag", etagContent);
      res.setHeader("Cache-Control", "no-cache");
      res.end(data);
    } else {
      res.statusCode = 404;
      res.end();
    }
  })
  .listen(3000, () => {
    console.log("http://localhost:3000");
  });
